﻿using Newtonsoft.Json;
using PermissionManager.BLL;
using PermissionManager.Model;
using PermissionsManager.Core;
using PermissionsManager.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace PermissionsManager.BLL
{
    public class AdminUserService : BaseService<AdminUser>
    {
        AdminUserRoleService adminUserRoleService = new AdminUserRoleService();
        ModuleUserServices moduleUserServices = new ModuleUserServices();

        /// <summary>
        /// 添加管理员  多表操作，管理员与组表
        /// </summary>
        /// <param name="adminUser"></param>
        /// <param name="moduleId"></param>
        /// <param name="createUserId"></param>
        /// <returns></returns>
        public bool AddAdmin(AdminUser adminUser, int createUserId, ModuleRole moduleRole)
        {
            //代码执行完，则释放资源   声明一个实例
            using (var db = new PermissionManagerEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //添加管理员表
                        adminUser.CreateTime = DateTime.Now;
                        db.AdminUser.Add(adminUser);
                        db.SaveChanges();
                        //组和管理员关联表
                        ModuleUser module = new ModuleUser();
                        module.ModuleId = moduleRole.ModuleId;
                        module.AdminUserId = adminUser.Id;
                        module.CreateTime = DateTime.Now;
                        module.CreateUserId = createUserId;
                        db.ModuleUser.Add(module);
                        db.SaveChanges();
                        //组和角色关联表
                        moduleRole.CreateTime = DateTime.Now;
                        module.CreateUserId = createUserId;
                        db.ModuleRole.Add(moduleRole);
                        db.SaveChanges();
                        //添加管理员角色
                        AdminUserRole adminUserRole = new AdminUserRole()
                        {
                            RoleId = moduleRole.RoleId,
                            AdminUserId = adminUser.Id,
                            CreateTime = DateTime.Now
                        };
                        db.AdminUserRole.Add(adminUserRole);
                        db.SaveChanges();
                        tran.Commit();
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="adminUser"></param>
        /// <param name="moduleId"></param>
        /// <param name="createUserId"></param>
        /// <returns></returns>
        public bool UpdateAdmin(AdminUser adminUser, int moduleId, int createUserId)
        {
            //代码执行完，则释放资源   声明一个实例
            using (var db = new PermissionManagerEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        AdminUser admin = db.AdminUser.Where(a => a.Id == adminUser.Id).FirstOrDefault();
                        admin.Name = adminUser.Name;
                        admin.Password = adminUser.Password;
                        admin.EmployeeName = adminUser.EmployeeName;
                        admin.Email = adminUser.Email;
                        //修改管理员表
                        db.Entry(admin).State = EntityState.Modified;
                        db.SaveChanges();
                        ModuleUser moduleUser= db.ModuleUser.Where(a=>a.AdminUserId==adminUser.Id).FirstOrDefault();
                        moduleUser.ModuleId = moduleId;
                        db.Entry(moduleUser).State = EntityState.Modified;
                        db.SaveChanges();
                        tran.Commit();
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 删除管理员  多表操作，管理员与组表
        /// </summary>
        /// <param name="adminUser"></param>
        /// <param name="moduleId"></param>
        /// <param name="createUserId"></param>
        /// <returns></returns>
        public bool DeleteAdmin(int id, int moduleId)
        {
            //代码执行完，则释放资源   声明一个实例
            using (var db = new PermissionManagerEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        AdminUser adminUser = db.AdminUser.FirstOrDefault(a => a.Id == id);
                        //删除管理员表
                        db.AdminUser.Remove(adminUser);
                        db.SaveChanges();
                        //删除管理员组关联
                        ModuleUser module = db.ModuleUser.FirstOrDefault(a => a.AdminUserId == id && a.ModuleId == moduleId);
                        db.ModuleUser.Remove(module);
                        db.SaveChanges();
                        ////删除管理员角色关联
                        AdminUserRole adminUserRole = db.AdminUserRole.FirstOrDefault(a => a.AdminUserId == id);
                        db.AdminUserRole.Remove(adminUserRole);
                        db.SaveChanges();
                        tran.Commit();
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="adminUser"></param>
        /// <param name="moduleId"></param>
        /// <param name="createUserId"></param>
        /// <returns></returns>
        public bool DeleteById(int[] Id)
        {
            //代码执行完，则释放资源   声明一个实例
            using (var db = new PermissionManagerEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        this.Delete(Id);
                        db.SaveChanges();
                        List<AdminUserRole> adminUserRoles = new List<AdminUserRole>();
                        List<ModuleUser> modules = new List<ModuleUser>();
                        foreach (var item in Id)
                        {
                            AdminUserRole adminUser = adminUserRoleService.Query(a => a.AdminUserId == item);
                            adminUserRoles.Add(adminUser);
                        }
                        foreach (var item in Id)
                        {
                            ModuleUser moduleUser1 = moduleUserServices.Query(a => a.AdminUserId == item);
                            modules.Add(moduleUser1);
                        }
                        foreach (var item in adminUserRoles)
                        {
                            adminUserRoleService.Delete(item);
                            db.SaveChanges();
                        }
                        foreach (var item in modules)
                        {
                            moduleUserServices.Delete(item);
                            db.SaveChanges();
                        }
                        tran.Commit();
                        return true;
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        return false;
                    }
                }
            }
        }


        /// <summary>
        /// 查询  三表关联
        /// </summary>
        /// <returns></returns>
        public List<AdminModuleUser> Query()
        {
            using (var db = new PermissionManagerEntities())
            {

                var result = from a in db.AdminUser
                             join b in db.ModuleUser    //关联“管理员表”与“组和管理员表”
                             on a.Id equals b.AdminUserId
                             join c in db.Module    //再关联“组表”
                             on b.ModuleId equals c.Id
                             select new AdminModuleUser()
                             {
                                 AdminId = a.Id,
                                 ModuleId = c.Id,
                                 ModuleName = c.Name,
                                 Name = a.Name,
                                 Remark = a.Remark,
                                 Email = a.Email,
                                 CreateTime = a.CreateTime
                             };
                return result.ToList();
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="EmployeeName"></param>
        /// <param name="CreateTime"></param>
        /// <returns></returns>
        public List<AdminModuleUser> Query(string EmployeeName, DateTime CreateTime)
        {
            using (var db = new PermissionManagerEntities())
            {
                var str = from a in db.AdminUser
                          join b in db.ModuleUser
                          on a.Id equals b.AdminUserId
                          join c in db.Module
                          on b.ModuleId equals c.Id
                          join d in db.AdminUserRole
                          on a.Id equals d.AdminUserId
                          where a.Name.Contains(EmployeeName) && a.CreateTime > (CreateTime)
                          select new AdminModuleUser()
                          {
                              AdminId = a.Id,
                              ModuleId = c.Id,
                              Name = a.Name,
                              ModuleName = c.Name,
                              Password = a.Password,
                              EmployeeName = a.EmployeeName,
                              CertNo = a.CertNo,
                              Email = a.Email,
                              Remark = a.Remark,
                              CreateTime = a.CreateTime
                          };
                return str.ToList();
            }
        }


        /// <summary>
        /// 登录校验
        /// </summary>
        /// <param name="adminUserView"></param>
        /// <returns></returns>
        public AdminUser ValidateLogin(AdminUser adminUser)
        {
            //调取接口
            string url = ConfigurationHelper.GetAppSettingeValue("apiUrl");
            string admin = HttpHelper.Get(url + "api/Login?moduleName=.NET01&username=" + adminUser.Name + "&pwd=" + adminUser.Password);
            return JsonConvert.DeserializeObject<AdminUser>(admin);
        }
    }
}
